package logic

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"github.com/zeromicro/go-zero/core/logx"
	"log"
	"month/rpc/internal/svc"
	"month/rpc/month"
	"strconv"
)

type EsJhLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewEsJhLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EsJhLogic {
	return &EsJhLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// es聚合
func (l *EsJhLogic) EsJh(in *month.EsSelRequest) (*month.EsResponse, error) {
	// todo: add your logic here and delete this line

	//初始化es连接
	esClient, err := elastic.NewClient(elastic.SetURL("http://43.143.123.142:9200"), elastic.SetSniff(false))
	if err != nil {
		return &month.EsResponse{
			Code:    400,
			Message: "elastic连接失败",
		}, err
	}

	aggs := elastic.NewSumAggregation().Field("Lz")

	res, err := esClient.Search().Index("fgit").Aggregation("avg_field_value", aggs).Do(context.Background())
	if err != nil {
		return &month.EsResponse{
			Code:    400,
			Message: "elastic聚合查询失败",
		}, err
	}

	ed, _ := json.Marshal(res.Aggregations)
	log.Println(string(ed))

	var ts t
	json.Unmarshal(ed, &ts)
	return &month.EsResponse{
		Code:    200,
		Message: "",
		Data:    strconv.Itoa(ts.Aggregations.AvgFieldValue.Value),
	}, nil
}

type t struct {
	Aggregations struct {
		AvgFieldValue struct {
			Value int `json:"value"`
		} `json:"avg_field_value"`
	} `json:"aggregations"`
}
